<template>
	<view>
		<view class="login-box">
			<uni-icons type="contact-filled" size="125" color="#ccc"></uni-icons>
			<button type="primary" class='login-btn' @click="getUserInfo">一键登录</button>
			<text>登录后尽享更多权益</text>
		</view>
	</view>
</template>

<script>
	import {mapMutations,mapState} from 'vuex';
	import {tokenData} from "@/api/user_request.js";
	export default {
		name:"my_login",
		data() {
			return {
				
			};
		},
		computed:{
			...mapState('user_m',['navigateInfo']),
		},
		methods:{
			...mapMutations('user_m',['updateUserInfo','updateToken','updateNavigateInfo']),
			//获取用户信息
			getUserInfo(){
				console.log('登录');
				let that = this;
				// 微信小程序 详情 本地设置 基础调试库 版本选择 2.25~2.27 其他版本无法使用下面的方法获取信息
				uni.getUserProfile({
					desc:"获取你的昵称、头像、地区及性别",
					success(info) {
						console.log(info);
						// 获取信息成功之后调用updateUserInfo,更新state当中的userInfo
						that.updateUserInfo(info.userInfo);
						that.getToken(info);
					},
					fail(err){
						console.log(err);
					}
				})
			},
			getToken(info){
				let that = this;
				const result = uni.login({
					//使用微信登录
					provider:'weixin',
					success: async (loginRes) => {
						console.log(loginRes);
						//寻找参数
						const query = {
							encryptedData : info.encryptedData,
							rawData : info.rawData,
							iv : info.iv,
							signature : info.signature,
							code : loginRes.code,
						};
						console.log(query);
						//发送post请求 获取token
						const result = await tokenData(query);
						console.log(result);
						//服务器不允许我们返回token
						//为了往下写  虚拟一个token
						// Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo
						//找到token之后 将token放到state token
						if(result.errMsg == 'request:ok'){
							let token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo';
							that.updateToken(token);
							//登录成功之后跳回之前的页面
							this.navigateBack();
						}
						
					},
					fail(err) {
						console.log(err);
						return uni.$showMsg('登录失败')
					}
				})
			},
			//返回登录之前的页面
			navigateBack(){
				console.log(this.navigateInfo);
				if(this.navigateInfo && this.navigateInfo.navigateType == 'switchTab'){
					uni.switchTab({
						url:this.navigateInfo.from,
						complete:()=>{
							console.log('跳回来');
							//跳回来之后将跳转的路径及方式置回
							this.updateNavigateInfo(null);
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
.login-box{
	height: 360px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 0 25px;
	border-top: 3px solid #c00000;
	.login-btn{
		width: 100%;
		border-radius: 50px;
		background-color: #c00000;
		margin-top: 10px;
	}
	text{
		font-size: 26rpx;
		margin-top: 15px;
		color: #a2a2a2;
	}
}
</style>
